# coding: utf-8
import threading
import time
import Queue
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
try:
    from Tkinter import *
    from tkMessageBox import *
    MODE = True
except ImportError:
    MODE = False

## source code refer to  http://codepad.org/UsMTbQQ3
## Create main window


class QuickEmail():

    def __init__(self):
        pass

    def send_email(self, smtp_server='smtp.qq.com', fromAddr='', toAddr='', login_user='', login_password='',
                    f_pic1=None):
        # Import the email modules we'll need


        # Open a plain text file for reading.  For this example, assume that
        # the text file contains only ASCII characters.
        # fp = open('d:/Table.txt', 'rb')
        # Create a text/plain message
        # msg = MIMEText(fp.read(), _charset='utf-8')
        # fp.close()

        # default is 'mixed', you can set it to 'alternative'
        # 试了一下好像不制定也可以发inline图和附件(开始一直不行，后来又可以了？)
        msg = MIMEMultipart()
        msg.preamble = 'Our family reunion'
        if not f_pic1:
            print 'using default image file to send!'
            with open(ur'd:/f.jpg', 'rb') as f_pic1:
                f_data1 = f_pic1.read()
        else:
            print 'using customzied image file to send!'
            f_data1 = f_pic1.read()
        with open(ur'd:/約.jpg', 'rb') as f_pic2:
            f_data2 = f_pic2.read()

        print 'files to send ->', f_pic1.name, f_pic2.name
        img_msg1 = MIMEImage(f_data1) # , _subtype='jpg')
        img_msg1.add_header('Content-ID', 'mypic')
        img_msg2 = MIMEImage(f_data2)
        img_msg2.add_header('Content-Disposition', 'attachment; filename=wtf.jpg')
        # img_msg2.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f_pic2.name))
        # msg = MIMEText(u'aaahey python! 你好', _charset='utf-8')

        msg['Subject'] = 'DEFAULT TITLE 默认标题'
        msg['From'] = fromAddr
        msg['To'] = toAddr
        msg.attach(MIMEText('Foxmail 圖片飛機123q <img src="cid:mypic">', _subtype='html', _charset='utf-8'))
        msg.attach(img_msg1)
        msg.attach(img_msg2)

        # Send the message via our own SMTP server, but don't include the
        # envelope header.
        s = smtplib.SMTP(smtp_server, port=25)
        s.login(login_user, login_password)
        s.sendmail(fromAddr, [toAddr], msg.as_string())
        s.quit()
        print 'done!', os.path.basename(f_pic2.name)


class GUIDemo:

    def __init__(self):
        
        self.root = Tk()
        self.root.title("Quick Send Email")
        self.root.resizable(False, False)
        self.file1 = None
        ## Communication queue
        self.commQueue = Queue.Queue()
        self.__initUI()

        ## Function run in thread
        def timeThread():
            import datetime as dt
            curTime = str(dt.datetime.now())
            while 1:
                ## Each time the time increases, put the new value in the queue...
                self.commQueue.put(curTime)
                ## ... and generate a custom event on the main window
                try:
                    self.root.event_add("<<TimeChanged>>", "<Button-1>")
                    self.root.event_generate('<<TimeChanged>>', when='tail', data="my_event")
                    print self.root.event_info("<<TimeChanged>>")
                ## If it failed, the window has been destoyed: over
                except TclError as e:
                    print e
                    # break
                ## Next
                time.sleep(1)
                curTime = curTime = str(dt.datetime.now())

    def __exit_me(self):
        import sys
        print "ok"
        sys.exit(0)

    def __send_handler(self):
        print 'send it invoked'
        ## get email infos
        fromAddr = self.strFromAddr.get()
        toAddr = self.strToAddr.get()
        login_user = self.strUserName.get()
        login_password = self.strPassword.get()

        isContinue = askyesno(title=u'發送', message=u'Are you sure to continue?', default=NO)
        if not isContinue:
            return
        if fromAddr.strip() == '' or toAddr.strip() == '' or login_user.strip() == '' \
                or login_password.strip() == '':
            showinfo('invalid', u'有内容没填写完整')
            return

        send_it = lambda: QuickEmail().send_email(fromAddr=fromAddr,
                                        toAddr=toAddr,
                                        login_user=login_user,
                                        login_password=login_password, f_pic1=self.file1)
        thread = threading.Thread(target=send_it)
        thread.start()

    def choose_file(self):
        import tkFileDialog
        f = tkFileDialog.askopenfile(mode='rb', title="choose a file to send",
                                     filetypes=[('All', '*.*'), ('images', '.png'), ('images', '.jpg'),
                                                ('images', '.gif'), ('images', '.bmp')])
        if f:
            self.file1 = f
            print self.file1

    def __printing(self):
        import datetime
        print "i'm printing", datetime.datetime.now()
        # with open(r'd:/c.txt', 'r') as av_file:
        #     c = av_file.readlines()
        #     print type(c), len(c)
        #     for each in c:
        #         print each,#unicode(each, 'utf-8'),
        f = open(r'd:/he.txt', 'r')
        for each in f:
            print each,

    def __initUI(self):
        ## In the main thread, do usual stuff
        frame = Frame(self.root)
        frame.pack()
        timeVar = IntVar()
        ## from address
        lblFromAddr = Label(frame, text=u'发件人: ', fg='red')
        lblFromAddr.grid(row=0, column=0, sticky=W)
        self.strFromAddr = StringVar()
        txtFromAddr = Entry(frame, textvariable=self.strFromAddr, relief=RAISED)
        txtFromAddr.grid(row=0, column=1, columnspan=4, sticky=W+E)

        ## to address
        lblToAddr = Label(frame, text=u'收件人: ', fg='blue')
        lblToAddr.grid(row=1, column=0, sticky=W)
        self.strToAddr = StringVar()
        txtToAddr = Entry(frame, textvariable=self.strToAddr, relief=RAISED)
        txtToAddr.grid(row=1, column=1, columnspan=4, sticky=W+E)

        ## username
        lblUserName = Label(frame, text=u'用户名(验证用): ', fg='blue')
        lblUserName.grid(row=2, column=0, sticky=W)
        self.strUserName = StringVar()
        txtUserName = Entry(frame, textvariable=self.strUserName, relief=RAISED)
        txtUserName.grid(row=2, column=1)

        ## password
        lblPassword = Label(frame, text=u'密码(验证用): ', fg='blue')
        lblPassword.grid(row=2, column=3, sticky=W)
        self.strPassword = StringVar()
        txtPassword = Entry(frame, textvariable=self.strPassword, show="*", relief=RAISED)
        txtPassword.grid(row=2, column=4)

        ## choose image button
        btnChooseFile = Button(frame, text='Choose...', command=self.choose_file)
        btnChooseFile.grid(row=3, column=0)

        ## send mail button
        btnSendEmail = Button(frame, text='发送', command=self.__send_handler)
        btnSendEmail.grid(row=3, column=1)

        ## print & exit button
        btnPrint = Button(frame, text='打印测试', command=self.__printing)
        btnPrint.grid(row=3, column=3)
        btnExit = Button(frame, text="退出", command=self.__exit_me)
        btnExit.grid(row=3, column=4)

        ## set email infos to default value
        me = "housedove@foxmail.com"
        self.strFromAddr.set(me)
        self.strToAddr.set(me)
        self.strUserName.set(me)
        self.strPassword.set(open('d:/pwd.txt', 'r').read())

        # Label(frame, textvariable=timeVar).grid(row=1, column=1)


        ## Use a binding on the custom event to get the new time value
        ## and change the variable to update the display
        def timeChanged(event):
            # print event.data
            timeVar.set(self.commQueue.get())

        self.root.bind('<<TimeChanged>>', timeChanged)

        ## Run the thread and the GUI main loop
        # th=threading.Thread(target=timeThread)
        # th.start()

        self.root.mainloop()

if __name__ == '__main__':
    a = GUIDemo()

